﻿namespace _08Net8AspNetCore_MiddleWare.Middlewares
{
    public class JSMiddleWare
    {
        public RequestDelegate next;

        public JSMiddleWare(RequestDelegate next)
        {
            this.next = next;
        }

        /// <summary>
        /// 获取html
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {

            string path = context.Request.Path.Value;
            if (path.Contains("js"))
            {
                await ResposeJS(context);
            }
            else
            {
                await this.next(context);
            }

        }


        /// <summary>
        /// 获取JS
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private static async Task ResposeJS(HttpContext context)
        {
            // 1、设置文件类型
            context.Response.ContentType = "text/Javascript";
            // 2、输出路径
            string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Index.js");
            // 3、读取文件内容
            var htmlContent = await File.ReadAllTextAsync(path);
            // 4、相应输出
            await context.Response.WriteAsync(htmlContent);
        }
    }

    /// <summary>
    /// JS 扩展
    /// </summary>
    public static class JSMiddleWareExtensions
    {
        public static void UseJS(this WebApplication app)
        {
            app.UseMiddleware<JSMiddleWare>();
        }
    }
}
